#!/bin/bash
HOSTNAME="localhost"
EMAIL_CONTENT=""
RANDOMLONG=""
RANDOMSHORT=""
REMOTEIP=""

HEADFILE=$1
CONTFILE=$2
TAILFILE=$3
IMAGEFILE=$4

HEADCONTENT=`cat $HEADFILE`
TAILCONTENT=`cat $TAILFILE`

Usage(){
	echo "sendmail.sh <head> <content> <tail> <image> <account>"
}

Random(){
	RANDOMLONG=`dd if=/dev/urandom count=128 bs=1 2>&1|md5sum|cut -b -25`
	RANDOMSHORT=`dd if=/dev/urandom count=128 bs=1 2>&1|md5sum|cut -b -15`
}

PrepareMail(){
#	AppendEContent "From:\"=?utf-8?B?""`echo 你好|base64`""?=\"<Edward@localhost.com>"
#	AppendEContent "To:$1"
#	AppendEContent "Date:""`date -R`"
	AppendEContent "Subject:=?utf-8?B?""`echo -E "$2"|base64`""?="
	Random
	AppendEContent "Message-Id:$RANDOMLONG@$RANDOMSHORT"
	AppendEContent "Content-Type: multipart/related;"
	AppendEContent "        boundary=\"_176_6FCAC368B40138458BCDF7B445CC2D4D579CB352EDCNHZEXCMS01al_\";"
	AppendEContent "        type=\"multipart/alternative\""
	AppendEContent "MIME-Version: 1.0"
	AppendEContent ""
	AppendEContent "--_176_6FCAC368B40138458BCDF7B445CC2D4D579CB352EDCNHZEXCMS01al_"
	AppendEContent "Content-Type: text/html;"
	AppendEContent "	charset=\"utf8\""
	AppendEContent "Content-Transfer-Encoding: base64"
	AppendEContent ""

	TEXTCONTENT=$HEADCONTENT
	TEXTCONTENT=$TEXTCONTENT$3
	TEXTCONTENT=$TEXTCONTENT$TAILCONTENT
	AppendEContent "`echo -E "$TEXTCONTENT"|base64 -w 76`"
	AppendEContent "`cat $IMAGEFILE`"
	echo "$EMAIL_CONTENT" >/tmp/$1.eml
}

AppendEContent(){
	EMAIL_CONTENT=$EMAIL_CONTENT$1$'\r'$'\n'
}

ClearEContent(){
	EMAIL_CONTENT=""
}

if [ $# -lt 4 ]
then
	Usage
	exit 1
fi

CONTENT=""
SUBJECT=""
i=0
exec 10<$CONTFILE
while read -u 10 SUBJECT
do
	read -u 10 CONTENT
	if [ $? -ne 0 ]
	then
		echo "enter the end of file"
		exit 1
	fi
	PrepareMail $i "$SUBJECT" "$CONTENT"
	ClearEContent
	i=$((i+1))
done
 

